<template>
	<picker class="form-item-picker" mode="multiSelector" @click="init" @change="changeAddress"
		@columnchange="columnChange" :value="cityIndex" :range="cityArray" range-key="name">
		<view class="region-value">{{cityValue}}</view>
	</picker>
</template>

<script setup>
	/**
	 * regionSelect 地区选择
	 * @description 地区三级联动选择
	 * @property {Array} defaultIndex 地址默认索引
	 * @property {String} defaultAddress 地址默认值
	 * @event {Function} onClick 点击事件
	 */
	import geo from './geo.json'
	const { proxy } = getCurrentInstance()

	const props = defineProps({
		defaultIndex: {
			type: Array,
			default () {
				return []
			}
		},
		defaultAddress: {
			type: String,
			default () {
				return ''
			}
		}
	})
	const emits = defineEmits([ 'changeRegion' ])

	//城市
	//整理后的原始数据
	const cityData = ref([])
	//显示在picker的数据格式
	const cityArray = ref([])
	const cityIndex = ref([0, 0, 0])
	const cityCode = ref('')
	const cityValue = ref('')

	onMounted(() => {
		init()
	})

	//初始化数据
	const init = () => {
		if (proxy.defaultIndex.length > 0) {
			cityIndex.value = proxy.defaultIndex
		}
		if (proxy.defaultAddress != '') {
			cityValue.value = proxy.defaultAddress
		}
		getCityData().then(res => {
			cityData.value = res.provinceData
			cityArray.value = res.cityArray
			if (cityValue.value != '') {
				getIndex('cityValue')
			} else if (proxy.defaultAddress != '') {
				getIndex('defaultAddress')
			} else {
				cityValue.value = '北京市市辖区东城区'
			}
		})
	}

	// 获取索引
	const getIndex = (type) => {
		let str = ''
		if (type == 'defaultAddress') {
			str = proxy.defaultAddress
		} else {
			str = cityValue.value
		}
		let reg = /.+?(省|市|自治区|自治州|行政区|县|区)/g // 省市区的正则
		let addressList = str.match(reg)
		if (addressList[0].trim() == '北京市' ||
			addressList[0].trim() == '天津市' ||
			addressList[0].trim() == '上海市' ||
			addressList[0].trim() == '重庆市') {
			let Regex = /.+?(市|市辖区|区)/g
			addressList = str.match(Regex)
		} else if (addressList[0].trim() == '香港特别行政区') {
			let Regex1 = /.+?(行政区|香港|界|岛|龙|区)/g
			addressList = str.match(Regex1)
		} else if (addressList[0].trim() == '澳门特别行政区') {
			let Regex2 = /.+?(行政区|岛|区)/g
			addressList = str.match(Regex2)
		}

		// 获取省市区索引
		let province = indexOfStr(cityData.value, addressList[0])
		let city = indexOfStr(cityData.value[province].children, addressList[1])
		let area = indexOfStr(cityData.value[province].children[city].children, addressList[2])

		// 设置显示在picker的第二列、第三列数据
		cityArray.value[1] = cityData.value[province].children
		cityArray.value[2] = cityData.value[province].children[city].children
		
		cityIndex.value = [province, city, area]
	}

	//选择城市
	const changeAddress = (e) => {
		cityIndex.value = e.detail.value
		let cityChangeIndex = e.detail.value
		let cityChangeArray = cityArray.value
		
		cityValue.value = cityChangeArray[0][cityChangeIndex[0]].name + cityChangeArray[1][cityChangeIndex[1]].name + (cityChangeArray[2][cityChangeIndex[2]] ? cityChangeArray[2][cityChangeIndex[2]].name : '')
		cityCode.value = cityChangeArray[2][cityChangeIndex[2]] ? cityChangeArray[2][cityChangeIndex[2]].code : cityChangeArray[1][cityChangeIndex[1]].code

		emits("changeRegion", {
			cityCode: cityCode.value,
			cityValue: cityValue.value,
			cityIndex: cityIndex
		})
	}
	
	// picker 列切换
	const columnChange = async (e) => {
		let column = e.detail.column
		let currentIndex = e.detail.value
		
		const cityDataChange = cityData.value
		let cityArrayChange = cityArray.value
		
		switch (column) {
			case 0:
				let arrayIndex = indexOf(cityArrayChange[0], cityArrayChange[0][currentIndex])
				let cityList = cityDataChange[arrayIndex].children
				let secondColumn = [] //存放第二列数据，即市的列
				let thirdColumn = [] //存放第三列数据，即县的列
				let areaList = []
				
				for (let i = 0; i < cityList.length; i++) {
					secondColumn.push({
						"code": cityList[i].code,
						"name": cityList[i].name,
						'province': cityList[i].province,
						'city': cityList[i].city
					})
				}
				areaList = cityList[0].children
				if (areaList && areaList.length > 0) {
					for (let j = 0; j < areaList.length; j++) {
						thirdColumn.push({
							"code": areaList[j].code,
							"name": areaList[j].name,
							'province': areaList[j].province,
							'city': areaList[j].city,
							"area": areaList[j].area
						})
					}
				}
				cityArray.value[1] = secondColumn
				cityArray.value[2] = thirdColumn
				cityIndex.value = [currentIndex, 0, 0]
				break;
			case 1:
				let arrayIndex21 = await indexOf(cityArrayChange[0], cityArrayChange[0][cityIndex.value[0]])
				let arrayIndex22 = await indexOf(cityArrayChange[1], cityArrayChange[1][currentIndex])
				let thirdColumn2 = [] //存放第三列数据，即县的列
				let areaList2 = cityDataChange[arrayIndex21].children[arrayIndex22].children;
				if (areaList2) {
					for (let j = 0; j < areaList2.length; j++) {
						thirdColumn2.push({
							"code": areaList2[j].code,
							"name": areaList2[j].name,
							'province': areaList2[j].province,
							'city': areaList2[j].city,
							"area": areaList2[j].area
						})
					}
				}

				cityArray.value[2] = thirdColumn2
				cityIndex.value = [cityIndex.value[0], currentIndex, 0];
				break;
			case 2:
				//滑动右列
				cityIndex.value = [cityIndex.value[0], cityIndex.value[1], currentIndex]
				break;
		}
	}

	//三级地址数据
	const getCityData = () => {
		return new Promise((resolve, reject) => {
			//定义三列空数组
			const cityArray = [
				[],
				[],
				[],
			]
			let provinceData = geo
			let cityList = []
			for (let i = 0; i < provinceData.length; i++) {
				cityArray[0].push({
					"code": provinceData[i].code,
					"name": provinceData[i].name,
					'province': provinceData[i].province
				})
				cityList = provinceData[cityIndex.value[0]].children
			}
			let areaList = []
			if (cityList && cityList.length > 0) {
				for (let j = 0; j < cityList.length; j++) {
					cityArray[1].push({
						"code": cityList[j].code,
						"name": cityList[j].name,
						'province': cityList[j].province,
						'city': cityList[j].city
					})
					areaList = cityList[cityIndex.value[1]].children
				}
			}
			if (areaList && areaList.length > 0) {
				for (let j = 0; j < areaList.length; j++) {
					cityArray[2].push({
						"code": areaList[j].code,
						"name": areaList[j].name,
						'province': areaList[j].province,
						'city': areaList[j].city,
						"area": areaList[j].area
					})
				}
			}
			resolve({
				cityArray,
				provinceData
			})
			uni.hideLoading()
		})
	}

	const indexOf = (arr, item) => {
		if (Array.prototype.indexOf) {
			return arr.indexOf(item)
		} else {
			for (var i = 0; i < arr.length; i++) {
				if (arr[i] === item) {
					return i
				}
			}
		}
		return -1;
	}

	const indexOfStr = (arr, str) => {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].name === str) {
				return i
			}
		}
		return -1
	}
</script>

<style lang="scss">
	.form-item-picker {
		width: 100%;
		height: 60rpx;
		position: relative !important;

		.region-value {
			width: 100%;
			position: absolute;
			top: 0;
			left: 0;
			height: 60rpx;
			line-height: 60rpx;
			font-size: 28rpx;
		}
	}
</style>
